//
//  CZStatusPictureView.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let MaxColumn = 3
private let ImageViewMargin: CGFloat = 4
// (屏幕的宽度 - 2 * CellMargin - (MaxColumn - 1) * ImageViewMargin) / MaxColumn
private let CZStatusPictureViewImageViewWH = (UIScreen.mainScreen().bounds.width - 2 * CellMargin - (CGFloat(MaxColumn) - 1) * ImageViewMargin) / CGFloat(MaxColumn)
class CZStatusPictureView: UIView {
 
    private var imageViews = [UIImageView]()
    
    var pictureURLs: [NSURL]? {
        didSet {
           let size = layoutImages(pictureURLs)
            self.snp_updateConstraints{ (make) -> Void in
                make.size.equalTo(size)
            }
        }
    }
    
    private func layoutImages(pictureURLs: [NSURL]?) -> CGSize{
        let count = pictureURLs?.count ?? 0
        var numberOfColumn = 3
        if count == 1{
            numberOfColumn = 1
        }else if count == 2 || count == 4{
            numberOfColumn = 2
        }
        var index = 0
        for imageView in imageViews{
            if index >= count{
                imageView.hidden = true
            }else{
                imageView.hidden = false
                let column = index % numberOfColumn
                let row = index / numberOfColumn
                let x = CGFloat(column) * (CZStatusPictureViewImageViewWH + ImageViewMargin)
                let y = CGFloat(row) * (CZStatusPictureViewImageViewWH + ImageViewMargin)
                imageView.frame = CGRect(x: x, y: y, width: CZStatusPictureViewImageViewWH, height: CZStatusPictureViewImageViewWH)
                let url = pictureURLs![index]
                imageView.sd_setImageWithURL(url)
            }
            
            index++
        }
        if count == 0 {
            return CGSizeZero
        }
        
        let numberOfRow = (count + numberOfColumn - 1) / numberOfColumn
        let width = CGFloat(numberOfColumn) * CZStatusPictureViewImageViewWH + (CGFloat(numberOfColumn) - 1) * ImageViewMargin
        let height = CGFloat(numberOfRow) * CZStatusPictureViewImageViewWH + (CGFloat(numberOfRow) - 1) * ImageViewMargin
        return CGSize(width: width, height: height)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
         prepareUI()
    }
    
    private func prepareUI(){
//        backgroundColor = UIColor.brownColor()
        for _ in 0..<9 {
            let imageView = UIImageView()
            imageView.backgroundColor = UIColor.randomColor()
            imageView.contentMode = UIViewContentMode.ScaleAspectFill
            imageView.clipsToBounds = true
            self.addSubview(imageView)
            imageViews.append(imageView)
        }
    }
    
    
}
